''''''

# Standard
# Related
import lx
# Local
import mosh.generic_utilities


_layerservice = lx.Service('layerservice')
_layerservice_query = _layerservice.query
_layerservice_select = _layerservice.select

def get_selected_uvs(mesh_id, vmap_index):
    '''Return a list of uvs in the modo form of tuple(poly_index, vert_index).

    Remember that if the layer index, or vmap index, is wrong, you may get
    odd results. This function does not do any form of error checking, and
    modo will often ignore wrong results and choose to give the last
    used "right" results instead of nothing. So, pay attention.

    @param mesh_id: The id of the mesh item.

    @param vmap_index: The index of the vmap.
    '''
    _layerservice_select('layer.name', mesh_id)

    _layerservice_select('vmap.name', str(vmap_index))

    _layerservice_select('uvs', 'selected')

    unformatted_uvs = _layerservice_query('uvs')

    # After a lot of testing, this seems to be the fastest way to handle
    # the conversion in large numbers.
    def convert_uv_strings(uv_string):
        poly_index, vert_index = uv_string[1:-1].split(',')
        return (int(poly_index), int(vert_index))

    if unformatted_uvs is None:
        return []
    else:
        return map(convert_uv_strings, unformatted_uvs)

def get_uv_position(mesh_id, uv_map_index, uv):
    '''Return the UV Coordinates of a.. uv.

    @param uv_map_index: The.. uv map index.
    
    @param mesh_id: The mesh's ID.

    @param uv: A tuple of what modo considers a uv, which is the polygon
    index, and the vertex index. (pi, vi)
    '''

    _layerservice_select('vmap.name', str(uv_map_index))

    _layerservice_select('layer.name', mesh_id)

    _layerservice_select('uv.pos', str((uv[0], uv[0],)))

    return _layerservice_query('uv.pos')
